package com.ygxsk.carhome.ui.livefee;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.FeeLiveOtherType;
import com.ygxsk.carhome.enumwrap.PropertyMentType;
import com.ygxsk.carhome.event.EventPaymentSubmint;
import com.ygxsk.carhome.event.RxFamilyMember;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.PropertyPaymentBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.PropertyPaymentAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

//import io.reactivex.functions.Consumer;
//import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
/*
 * @Author:itchenqi175@163.com
 * @Time:2024/2/19  10:12
 * @Description:物业费的缴费列表
 */
public class PropertyPaymentActivity extends ErrorActivity implements ErrorParentExtraSingle {


    @BindView(R.id.refreshlayoutpropertypayment)
    SmartRefreshLayout refreshLayoutPropertyPayment;//包裹刷新布局

    @BindView(R.id.recyclerviewinpropertypayment)
    RecyclerView recyclerViewInPropertyPayment;//列表布局

    @BindView(R.id.layoutbuttoncheckcontent)
    RelativeLayout layoutButtonContent;//底部的布局内容

    @BindView(R.id.relacontentquanxuan)
    RelativeLayout relaContentQuanXuan;//全选按钮

    @BindView(R.id.imageViewUnSelectquanxuan)
    CheckBox imageViewUnSelectQuanXuan;//全选的对勾checkbox

    /**
     * 下一步按钮
     */
    @BindView(R.id.buttonnextround)
    com.flyco.roundview.RoundTextView buttonNext;

    //支付的总金额
    @BindView(R.id.textviewamount)
    TextView textViewAmount;

    private String messageNull = "暂无待缴费用~";
    /**
     * 房间编号文本信息内容
     */
    private TextView textviewRoom;

    public interface ChooseListener {

        //2018年08月09日去掉全选功能的
        void chooseAllItem();

        void unChooseAllItem();

    }

    /**
     * 该界面是从哪里跳转过来的标志
     */
    private int jumpFromFlag;

    /**
     * 该列表的适配器内容
     */
    private PropertyPaymentAdapter propertyPaymentAdapter;

    /**
     * 标记选中和未选中两种状态
     */
    private boolean isSelectAll;

    /**
     * 上传房间id的编号
     */
    private String houseIdPass = "";
    /**
     * 最后一条缴费单号的id
     */
    private String housePaymentIdPass = "";

    /**
     * 接收数据内容
     */
    private ArrayList<PropertyPaymentBean> mDataResources = new ArrayList<>();

    /**
     * 选择房间按钮
     */
    //@OnClick(R.id.buttonnextround)//因为去掉【全选】所以去掉【全选】的功能按钮
    @OnClick({R.id.buttonnextround, R.id.relacontentquanxuan})//原始代码内容 2021年12月6日17:13:41又添加上【全选】的内容
    public void clickInPropertyPayMent(View view) {

        switch (view.getId()) {

            case R.id.buttonnextround: {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (NetworkUtils.isConnected()) {

                        //做循环判断
                        ArrayList<String> arrayList = new ArrayList<>();

                        for (int index = 0; index < mDataResources.size(); index++) {

                            int isCheckedin = mDataResources.get(index).getChecked();

                            if (isCheckedin == 1) {
                                arrayList.add(mDataResources.get(index).getHousePaymentId());//添加id类
                            } else {
                                //retain
                            }

                        }
                        //选择房间编号 也要判断。未选择房间编号不让跳转
                        //String roomName = textviewRoom.getText().toString();

                        //2018年03月21日，需求 房间号不是必选的。
                /*if (TextUtils.isEmpty(roomName)){

                    new AlertView("",//
                            "请选择房间", //
                            null,//
                            new String[]{ConstantApi.ALERT_SINGLE}, //
                            null, //
                            PropertyPaymentActivity.this, //
                            AlertView.Style.Alert,//
                            new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int position) {
                                    //
                                }
                            })//
                            .setCancelable(true)
                            .show();//

                    return;
                }*/


                        if (!arrayList.isEmpty()) {

//                          //需要携带信息吗？
                            Bundle bundle = new Bundle();

                            //携带金额和房间号。应该还有房间ID内容
                            //bundle.putString(ConstantApi.EXTRA_PAYMENT_ROOMNUMBER,roomName);//房间号可以不携带
                            //必须携带是从哪儿跳转的
                            bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, jumpFromFlag);
                            bundle.putString(ExtraKey.EXTRA_PAYMENT_AMOUNT, CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)).toString());//携带金额过去
                            bundle.putStringArrayList(ExtraKey.EXTRA_PAYMENT_HOUSEPAYMENTIDS, arrayList);//携带缴费id信息内容

                            ActivityUtils.startActivity(bundle, PaymentFeeActivity.class);

                        } else {

                            CommUtils.checkDialog(mAlertView);

                            mAlertView = new AlertView(getResources().getString(R.string.clearaddorsubmitsuretitletips),//
                                    getString(R.string.choose_payment_item), //
                                    null,//
                                    new String[]{ConstantSign.ALERT_SINGLE}, //
                                    null, //
                                    PropertyPaymentActivity.this, //
                                    AlertView.Style.Alert,//
                                    new OnItemClickListener() {//
                                        @Override
                                        public void onItemClick(Object o, int position) {
                                            //
                                        }
                                    });

                            mAlertView.setCancelable(true)//
                                    .show();//

                        }

                    } else {
//                        CommUtils.displayToastShort(PropertyPaymentActivity.this, ConstantApi.NETWORKFAIL);
                        ToastUtils.showShort(getResources().getString(R.string.http_exception_network));
                    }

                }

                break;
            }

            //2018年08月09日去掉全选功能，去掉这个全选的外侧点击事件功能
            //2021年12月6日17:14:12 添加全选的按钮的功能
            case R.id.relacontentquanxuan: {
                method_selectAll();
                break;
            }

            default:
                break;
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        mCompositeDisposable.add(RxBus.getInstance().toObserverable(RxFamilyMember.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxFamilyMember>() {//
                    @Override
                    public void accept(final RxFamilyMember rxFamilyMember) throws Exception {

                        if (rxFamilyMember.getMessage() == ExtraValue.RXBUS_PROPERTYPAYMENT) {

                            if (textviewRoom != null) {
                                textviewRoom.post(new Runnable() {
                                    @Override
                                    public void run() {

                                        CommUtils.setText(textviewRoom, rxFamilyMember.getRoomBean().getHouseNo());

                                        housePaymentIdPass = "";//重新选择房间就是筛选条件。
                                        houseIdPass = rxFamilyMember.getRoomBean().getHouseId();

                                        //2018年03月21日，选择房间，筛选列表，房间不是必选的
                                        if (!mDataResources.isEmpty()) {
                                            mDataResources.clear();
                                        }

                                        //2018年08月09日去掉全选功能,即便是重新选择了房间编号，也需要将费用做成全选的状态
                                        //稍微做一下释放，让所有勾选均不勾选。
                                        chooseListenerFunction.unChooseAllItem();

                                        method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));

                                        //选中完毕房间号 立即发起重新查询
//                                        getServerDatas(houseIdPass, housePaymentIdPass);
//                                        getServerDatas(houseIdPass, housePaymentIdPass);
                                        getServerDatas();

                                    }
                                });
                            }
                        }
                    }
                }));

        //bug:漏加导致物业费和租赁费支付完毕，页面没有刷新
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        gainDatas();

    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }


    //将来用到再放开，不用到暂时屏蔽
//    private View getHeaderView(RecyclerView _recyclerViewWork) {
//
//        View workHeader;
//        if ((_recyclerViewWork != null) && (_recyclerViewWork.getParent() != null)) {
//            workHeader = LayoutInflater.from(PropertyPaymentActivity.this).inflate(//
//                    R.layout.propertypaymentheader, //
//                    (ViewGroup) _recyclerViewWork.getParent(),//
//                    false);//
//        } else {
//            workHeader = LayoutInflater.from(PropertyPaymentActivity.this).inflate(R.layout.propertypaymentheader, null);
//        }
//
//        //包裹外侧的布局
//        RelativeLayout layoutSelectRoom = (RelativeLayout) workHeader.findViewById(R.id.layoutselectroom);
//        //房间号
//        textviewRoom = (TextView) workHeader.findViewById(R.id.textviewroom);
//
//        layoutSelectRoom.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                //跳转到选择房间界面，而且要携带数据回来
//                Bundle bundle = new Bundle();
//                bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.RXBUS_PROPERTYPAYMENT);
//                //给上次选中的房间编号携带过去，方便区分上次选中的内容
//                if (!TextUtils.isEmpty(houseIdPass)) {
//                    bundle.putString(ExtraKey.EXTRA_PROPERTYPAYMENTHOUSEIDPASS, houseIdPass);
//                }
//
////                ActivityUtils.startActivity(bundle, SelectRoomActivity.class);
//
//            }
//        });
//
//        return workHeader;
//    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_property_payment;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        processExtraData();

        if (jumpFromFlag == FeeLiveOtherType.TYPE_PROPERTY.getIndex()) {
            toolbarHelper.setTitle(getString(R.string.title_property_payment));
        } else if (jumpFromFlag == FeeLiveOtherType.TYPE_RENTAL.getIndex()) {
            toolbarHelper.setTitle(getString(R.string.title_rental_payment));
        }

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutRight(true, 1, getString(R.string.payment_history), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //物业缴费记录

                //携带标志是物业费还是租赁费
                Bundle extra_bundle = new Bundle();
                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, jumpFromFlag);

                ActivityUtils.startActivity(extra_bundle, PaymentNotesActivity.class);

            }
        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    //private void getServerDatas(String _houseId, String _housePaymentId) {
    private void getServerDatas() {

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "jumpFromFlag--是什么  -->" + jumpFromFlag);

        //区分是 物业缴费 还是 租赁费
        if (jumpFromFlag == FeeLiveOtherType.TYPE_PROPERTY.getIndex()) {

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "TYPE_PROPERTY-物业缴费");

            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETHOUSEPAYMENTFORREMOTE_URL);
            addLogUpLoadInfo.setUrlPath(ApiService.getHousePaymentForRemote_url);
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getHousePaymentForRemote(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(PropertyPaymentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<PropertyPaymentBean>>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            CommUtils.checkMaterialDialog(materialDialog);
                            methodNotSuccessData(what_method, serverCode, serverMessage);
                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {

//                            CommUtils.checkMaterialDialog(materialDialog);
                            method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                            loadingGone();

                        }
                    }).subscribe(new Consumer<ArrayList<PropertyPaymentBean>>() {
                        @Override
                        public void accept(ArrayList<PropertyPaymentBean> propertyPaymentBeanArrayList) throws Throwable {

                            method_handler_success(propertyPaymentBeanArrayList);

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }

                        }
                    });


        } else if (jumpFromFlag == FeeLiveOtherType.TYPE_RENTAL.getIndex()) {

            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETHOUSEPAYMENTLIST_URL);
            addLogUpLoadInfo.setUrlPath(ApiService.getHousePaymentList_url);
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getHousePaymentList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(PropertyPaymentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<PropertyPaymentBean>>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            CommUtils.checkMaterialDialog(materialDialog);
                            methodNotSuccessData(what_method, serverCode, serverMessage);
                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {

//                            CommUtils.checkMaterialDialog(materialDialog);
                            method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                            loadingGone();

                        }
                    }).subscribe(new Consumer<ArrayList<PropertyPaymentBean>>() {
                        @Override
                        public void accept(ArrayList<PropertyPaymentBean> propertyPaymentBeanArrayList) throws Throwable {

                            method_handler_success(propertyPaymentBeanArrayList);

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }

                        }
                    });
        }

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        if (what_method == ConstantApi.WHAT_GETHOUSEPAYMENTLIST_URL || what_method == ConstantApi.WHAT_GETHOUSEPAYMENTFORREMOTE_URL) {

            if (mDataResources != null && mDataResources.isEmpty()) {

                setEnableLoadmore(refreshLayoutPropertyPayment, false);

                CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                        serverCode,//
                        R.drawable.errorsear,//
                        serverMessage,//
                        getString(R.string.nulldatanow));

            }

        }

    }

    /**
     * @param propertyPaymentBeanArrayList 物业费和租赁费通用处理数据成功的方法
     */
    private void method_handler_success(ArrayList<PropertyPaymentBean> propertyPaymentBeanArrayList) {

        CommUtils.checkMaterialDialog(materialDialog);

        if (propertyPaymentBeanArrayList != null && !propertyPaymentBeanArrayList.isEmpty()) {

            if (mDataResources != null) {
                mDataResources.addAll(propertyPaymentBeanArrayList);
            }

        }

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void initViews() {

        //默认都是未选中的false内容。
//        CommUtils.setButtonDrawable(imageViewUnSelectQuanXuan);
        recyclerViewInPropertyPayment.setLayoutManager(new MyLinearLayoutManager(this));

        //添加分割线内容
//        recyclerViewPayment.addItemDecoration(new DividerItemDecorationInPaymentList(PropertyPaymentActivity.this));

//        public enum PropertyMentType {
//            TYPE_TO_BE_PAY("1", "待支付"),
//            TYPE_GO_TO_PAY("2", "去结算");

//        propertyPaymentAdapter = new PropertyPaymentAdapter(R.layout.paymentlistadapter, mDataResources, 1, mSession);
//        propertyPaymentAdapter = new PropertyPaymentAdapter(R.layout.paymentlistadapter, mDataResources, PropertyMentType.TYPE_TO_BE_PAY.getIndex());

        propertyPaymentAdapter = new PropertyPaymentAdapter(R.layout.propertypaymentadapter, mDataResources, PropertyMentType.TYPE_TO_BE_PAY.getIndex());

//        propertyPaymentAdapter.removeAllHeaderView();
//        propertyPaymentAdapter.addHeaderView(getHeaderView(recyclerViewInPropertyPayment));

        recyclerViewInPropertyPayment.setAdapter(propertyPaymentAdapter);

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
        }

        //2018年08月09日填充去掉单个勾选功能，如下一整段代码都是 start================================================================================================
        //2021年12月6日17:08:39 要打开勾选的功能，如下一整段代码都是 start================================================================================================
        //这里为了扩大点击区域 使用整条列表内容
        propertyPaymentAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //这个不需要做快速双击的判断内容
                PropertyPaymentBean propertyPaymentBean = (PropertyPaymentBean) adapter.getItem(position);

                //2018年09月15日检查腾讯bugly代码发现有空指针异常，假如这块放开那么要对propertyPaymentBean做null判断。
                //如果选中的是checkbox布局内容
                int isChecked = propertyPaymentBean.getChecked();
                //ToastUtils.showShort("点击了图片内容");
                if (isChecked == 0) {
                    propertyPaymentBean.setChecked(1);

                } else if (isChecked == 1) {
                    propertyPaymentBean.setChecked(0);
                }

                //采集当前列表的选中状态
                ArrayList<Boolean> tempBooleans = new ArrayList<>();

                for (int index = 0; index < mDataResources.size(); index++) {
                    int currentState = mDataResources.get(index).getChecked();
                    if (currentState == 0) {
                        tempBooleans.add(false);
                    } else if (currentState == 1) {
                        tempBooleans.add(true);
                    }
                }

                for (int pos = 0; pos < mDataResources.size(); pos++) {

                    int curState = mDataResources.get(pos).getChecked();

                    if (curState == 0) {//如果发现有一个未选中,取消全选状态，终止循环。
                        chooseListenerFunction.unChooseAllItem();
                        break;

                    } else if (curState == 1) {
                        //如果发现有一个是选中状态，可以不管，如果发现所有列表全是选中状态，则全选勾中
                        if (tempBooleans.contains(false)) {
                            //如果有包含未选中的(换言之就是:列表里有未被选中的,那么可以忽略)
                        } else {
                            chooseListenerFunction.chooseAllItem();
                            break;
                        }
                    }
                }

                //这里需要重新刷新 因为列表有复用的情况
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }

                //价钱总量内容
                method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));

            }
        });

        //没有分页
        //点击这里 不可以点击查看详情内容。
//        refreshLayoutPropertyPayment.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//
//                refreshLayout.getLayout().post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        //正常加载，携带最后一条缴费的id
////                        getServerDatas(houseIdPass, housePaymentIdPass);
//                        getServerDatas();
//
//                        refreshLayout.finishLoadMore();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//
//                refreshLayout.getLayout().post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        houseIdPass = "";//reset
//                        housePaymentIdPass = "";//reset
//                        if (textviewRoom != null) {
//                            textviewRoom.setText("");
//                        }
//                        //最后一条商品id 重置
//                        if (!mDataResources.isEmpty()) {
//                            mDataResources.clear();
//                        }
//
//                        //清空总钱量
//                        //2018年08月09日去掉全选功能,即便是刷新也要设置成全部选中
//                        //稍微做一下释放
//                        chooseListenerFunction.unChooseAllItem();
//                        method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));
//
//                        if (NetworkUtils.isConnected()) {
//
////                            getServerDatas(houseIdPass, housePaymentIdPass);
//                            getServerDatas();
//
//                        } else {
//
//                            netWorkError();
//                            CommUtils.setViewGone(layoutButtonContent);
//                            setEnableLoadmore(refreshLayoutPropertyPayment, false);
//
//                        }
//
//                        refreshLayout.finishRefresh();
//                    }
//                });
//
//            }
//        });

        refreshLayoutPropertyPayment.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        houseIdPass = "";//reset
                        housePaymentIdPass = "";//reset

                        if (textviewRoom != null) {
                            textviewRoom.setText("");
                        }

                        //最后一条商品id 重置
                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        //清空总钱量
                        //2018年08月09日去掉全选功能,即便是刷新也要设置成全部选中
                        //稍微做一下释放
                        chooseListenerFunction.unChooseAllItem();

                        method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));

                        if (NetworkUtils.isConnected()) {
//                            getServerDatas(houseIdPass, housePaymentIdPass);
                            getServerDatas();

                        } else {

                            netWorkError();

                            CommUtils.setViewGone(layoutButtonContent);
//                            setEnableLoadmore(refreshLayoutPropertyPayment, false);

                        }

                    }
                });

                refreshLayout.finishRefresh();

            }
        });


    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

//            getServerDatas("", "");

            //区分是物业缴费，还是租赁费

            getServerDatas();

        } else {

            netWorkError();
//            setEnableLoadmore(refreshLayoutInLeadsActivity, false);

        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    private ChooseListener chooseListenerFunction = new ChooseListener() {

        @Override
        public void chooseAllItem() {

            if (propertyPaymentAdapter != null) {

                if (!isSelectAll) {//如果未被选中
                    //2018年08月09日修改的说是全选功能暂时去掉如下四行代码
                    isSelectAll = true;
                    imageViewUnSelectQuanXuan.setChecked(true);
                    //如果都未被选中，那么选中
                    propertyPaymentAdapter.selectedAll();
                    //重新计算价格
                    method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));

                } else if (isSelectAll) {//如果此刻是被选中的
                    //2018年08月09日修改的说是全选功能暂时去掉如下四行代码
                    //===============================================================================
                    isSelectAll = false;
                    imageViewUnSelectQuanXuan.setChecked(false);
                    propertyPaymentAdapter.unSelectedAll();
                    //重新计算价格
                    method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));
                    //===============================================================================
                }

            }

        }

        //2018年08月09日添加全选不可用且中间不让点击内容
        @Override
        public void unChooseAllItem() {
            //2018年08月09日添加全选不可用且中间不让点击内容
            //如果不被全选中
            //================================================================================
            isSelectAll = false;
            imageViewUnSelectQuanXuan.setChecked(false);
            method_totalPrice(CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)));
            //================================================================================
        }
    };

    //2018年08月10日添加提取全选功能
    private void method_selectAll() {
        //默认是确定选中全选
        if (!mDataResources.isEmpty()) {
            //2018年08月09日去掉全选功能
            chooseListenerFunction.chooseAllItem();
        } else {
//            CommUtils.displayToastShort(PropertyPaymentActivity.this, "暂无数据");
            ToastUtils.showShort(getResources().getString(R.string.nulldatanow));
        }
    }

    /**
     * 填充总价格内容
     */
    private void method_totalPrice(final BigDecimal _totalPrice) {

        //CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)

        if (textViewAmount != null) {
            textViewAmount.post(new Runnable() {
                @Override
                public void run() {
                    CommUtils.setText(textViewAmount, mSession.getCurrencySymbol() + _totalPrice.toString());//
                }
            });
        }
    }

    private BigDecimal methodToatal(ArrayList<PropertyPaymentBean> _datas) {

        BigDecimal curPriceTotal = new BigDecimal(0);

        if ((_datas != null) && (!_datas.isEmpty())) {

            for (int index = 0; index < _datas.size(); index++) {

                PropertyPaymentBean item = _datas.get(index);

                int isChecked = item.getChecked();

                if (isChecked == 1) {//被勾选的参与计算
                    BigDecimal fee = item.getPayAmount();
                    curPriceTotal = curPriceTotal.add(fee);
                } else {
                    //未被选中，不参与结算。
                }

            }

        } else {
            //不参与运算的
            return curPriceTotal;
        }

        return curPriceTotal;

    }

    @Override
    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();
        //use the data received here

        if (bundle != null) {
            jumpFromFlag = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--jumpFromFlag-->" + jumpFromFlag);
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadEventPayMent(EventPaymentSubmint eventPaymentSubmint) {

        if (eventPaymentSubmint.getMessage() == ExtraValue.EVENTBUS_EVENTPAYMENTSUBMINT) {

            LogUtils.d("itchen---收到通知缴费列表刷新");

            //清空列表信息
            if (mDataResources != null && !mDataResources.isEmpty()) {
                mDataResources.clear();
            }

            if (propertyPaymentAdapter != null) {
                propertyPaymentAdapter.notifyDataSetChanged();
            }

            gainDatas();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        jumpFromFlag = 0;//reset

        houseIdPass = "";//reset

        housePaymentIdPass = "";//reset

        //清空房间编号
        if (textviewRoom != null) {
            if (!TextUtils.isEmpty(textviewRoom.getText().toString().trim())) {
                textviewRoom.setText("");
                //LogUtils.d("itchen---清空房间编号");
            }
        }

        //清空列表信息
        if ((mDataResources != null) && (!mDataResources.isEmpty())) {
            mDataResources.clear();
            //LogUtils.d("itchen---清空列表");
        }

        if (propertyPaymentAdapter != null) {
            propertyPaymentAdapter.notifyDataSetChanged();
            propertyPaymentAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        //=======================================================================

        if (mAlertView != null) {
            if (mAlertView.isShowing()) {
                mAlertView.dismiss();
                mAlertView = null;
            }
        }

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }

        EventBus.getDefault().unregister(this);
        //LogUtils.d("itchen----PropertyPaymentActivity--onDestroy");

    }
}